package com.jk.contrller;

import com.jk.dao.EsCloth;
import com.jk.dao.EsDao;
import com.jk.entity.ClothEntity;
import com.jk.entity.ShopCartEntity;
import com.jk.service.EsService;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("es")
public class EsController {

    @Autowired
    private EsService esService;

    @Autowired
    private EsCloth esCloth;

    // 查询时需要
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate ;


    //elasticsearch 生成表
    //   @RequestMapping("el")
    //   @ResponseBody
    //   public   void  el(){

    //      List<ElasticsearchBean> list=shoppService.queryelasticsearch();
    //      for (ElasticsearchBean ss: list) {
    //          ss.setScrenicName(ss.getScrenicName()+""+ss.getHotelName());
    //       }
    //       elasticsearch.saveAll(list);

    //   }

    //更新es服务器数据
    @RequestMapping("addEs")
    public boolean addClothEs() {
        List<ClothEntity> list = esService.queryShopCart();//先去后台查出数据在赋值
        ClothEntity cloth = new ClothEntity();
        try {
            for (int i = 0; i < list.size(); i++) {
                cloth.setClothId(Integer.valueOf(list.get(i).getClothId().toString()));
                cloth.setClothName(list.get(i).getClothName());
                esCloth.save(cloth);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    //es搜索商品
    @RequestMapping("queryShop")
    public List  ellist(@RequestParam String name, HttpSession session){
        if (name==null||"".equals(name)){
            name = session.getAttribute("name").toString();
        }

        HashMap<String, Object> resultMap = new HashMap<>();
        //创建一个要搜索的索引库
        SearchRequestBuilder searchRequestBuilder = elasticsearchTemplate.getClient().prepareSearch("clo_cloth").setTypes("clothentity");


        //创建组合查询
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        if (name!=null && !"".equals(name)){
            boolQueryBuilder.should(QueryBuilders.matchQuery("clothName",name));
        }
        //设置查询的类型
        searchRequestBuilder.setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
        searchRequestBuilder.setQuery(boolQueryBuilder);

        //设置高亮字段
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("clothName")
                .preTags("<font color='red'>")
                .postTags("</font>");
        searchRequestBuilder.highlighter(highlightBuilder);

        //直接搜索返回响应数据 （json）
        SearchResponse searchResponse = searchRequestBuilder.get();
        SearchHits hits = searchResponse.getHits();
        //获取总条数
        long totalHits = hits.getTotalHits();
        resultMap.put("total",totalHits);

        ArrayList<Map<String,Object>> list = new ArrayList<>();
        //获取Hits中json对象数据
        SearchHit[] hits1 = hits.getHits();
        for (int i=0;i<hits1.length;i++){
            //获取Map对象
            Map<String, Object> sourceAsMap = hits1[i].getSourceAsMap();
            //获取高亮字段
            Map<String, HighlightField> highlightFields = hits1[i].getHighlightFields();
            //！！如果有高亮字段就取出赋给上面sourceAsMap中原有的名字给他替换掉！！
            if (name!=null && !"".equals(name)){
                sourceAsMap.put("clothName",highlightFields.get("clothName").getFragments()[0].toString());
            }
            list.add(sourceAsMap);
        }
        return list;
    }
}
